package com.abe.gcore.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class IBaseF extends Fragment {

    public View rootView;

    private Unbinder unbinder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(getLayoutResId(), container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initDatas();
    }


    /**
     * 处理传值
     */
    public HashMap<String, Object> getFilter() {
        if (getArguments() != null && getArguments().containsKey("filter")) {
            HashMap<String, Object> filter = (HashMap<String, Object>) getArguments()
                    .getSerializable("filter");
            return filter;
        }
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    /**
     * 获取context
     */
    public Context getThisContext() {
        return getActivity();
    }


    /**
     * 初始化
     */
    protected abstract void init();

    /**
     * 返回布局资源ID
     */
    protected abstract int getLayoutResId();

    /**
     * 实现功能，填充数据
     */
    protected abstract void initDatas();

    /**
     * 跳转到指定页面
     */
    public void goToActivity(Class<?> cls) {
        goToActivity(cls, null);
    }

    /**
     * 跳转到指定页面
     */
    public void goToActivity(Class<?> cls, HashMap<String, Object> filter) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (filter != null) {
            intent.putExtra("filter", filter);
        }
        startActivity(intent);
    }

    /**
     * 跳转到指定页面
     */
    public void goToActivityForResult(Class<?> cls, int code) {
        goToActivityForResult(cls, code, null);
    }

    /**
     * 跳转到指定页面
     */
    public void goToActivityForResult(Class<?> cls, int code,
                                      HashMap<String, Object> filter) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (filter != null) {
            intent.putExtra("filter", filter);
        }
        startActivityForResult(intent, code);
    }
}
